#pragma once
#include "reactor/tcp_server.hpp"
#include "search/keyword_recommend.hpp"
#include "search/page_search.hpp"
#include "util/protocol.hpp"
#include <memory>
#include <mutex>
#include <map>

// 前向声明，避免在头文件中引入 reactor 内部实现
namespace reactor {
class EventLoop;
class Buffer;
class TcpConnection;
}

class SearchServer {
public:
    SearchServer(const std::string& ip, uint16_t port, int threadNum = 4);
    ~SearchServer();

    // 初始化服务，加载所有离线数据
    bool init(const std::string& cnDict, const std::string& cnIndex,
              const std::string& enDict, const std::string& enIndex,
              const std::string& invertedIndex, const std::string& pages,
              const std::string& offsets);
    
    // 启动服务，开始监听事件
    void start();

private:
    // 网络事件回调
    void onConnection(const std::shared_ptr<reactor::TcpConnection>& conn);
    void onMessage(const std::shared_ptr<reactor::TcpConnection>& conn, reactor::Buffer* buf);
    
    // 业务逻辑处理
    std::string handleKeywordRecommend(const std::string& query);
    std::string handlePageSearch(const std::string& query);
    
private:
    std::unique_ptr<reactor::EventLoop> _mainLoop;
    reactor::TcpServer _server;
    
    KeywordRecommend _keywordRecommend; // 关键字推荐模块
    PageSearch _pageSearch;             // 网页搜索模块

    // 每个连接都应该有自己的解析器，以处理并发请求
    std::mutex _parsersMutex;
    std::map<int, protocol::MessageParser> _parsers; 
};
